import {GetCountdownTimer, SetCountdownTimer, GetUserConfig, BarTime, HumanTime, setIcon} from './common.js';

/**
 * @since 2024-09-23 全局参数
 *
 * timer          用户定时信息，避免每次读缓存
 * alarmTime      函数执行间隔
 * alarmName      闹钟的名称
 *
 * badgeText      图标上显示的信息，text+bgColor
 * sameTextCount  设置图标上信息，相同的次数
 * showCount      更新图标上信息的次数
 */
let timer = null, alarmTime = 0, alarmName = "timer-alarm";
let badgeText = null, sameTextCount = 0, showCount = 0;

/**
 * @description 更新插件图标
 * @author start2004
 * @since 2024-09-23
 *
 * @return {null}
 */
async function UpdateTimeBar() {
  /**
   * @since 2024-09-23 读取配置
   */
  // console.log("倒计时配置", timer);
  if(timer === null) timer = await GetCountdownTimer();
  // console.log("UpateTimeBar函数执行", Date());

  /**
   * @since 2024-09-23 倒计时暂停
   */
  if(timer.pause){
    BarTextTime(timer.pausetime, "#ffa116");

    /**
     * @since 2024-09-23 清除定时任务
     */
    ClearAlarm();
    return ;
  } else {}

  /**
   * @since 2024-09-23 倒计时结束
   */
  if(timer.done){
    BarTextTime("");

    /**
     * @since 2024-09-23 清除定时任务
     */
    ClearAlarm();
    SetCountdownTimer(timer);

    return ;
  } else {}

  /**
   * @since 2024-09-23 计算时间差
   */
  let now = parseInt(new Date().getTime() / 1000);
  let diff = timer.endtime - now;
  if(diff > 0){
    BarTextTime(diff);

    /**
     * @since 2024-09-23 启动定时任务
     * @since 2025-09-03 调整定时，避免频繁
     */
    let sec = Math.min(10, diff);

    /**
     * @since 2025-09-03 间隔不一致
     * @since 2025-09-03 删除闹钟，重新建闹钟
     */
    if(sec !== alarmTime) CreateAlarm(sec);
  } else {
    console.log("超时提醒", Math.abs(diff), "秒");

    /**
     * @since 2024-09-23 倒计时结束信息保存
     */
    timer.done = true;
    timer.lastendtime = timer.endtime;
    SetCountdownTimer(timer);

    /**
     * @since 2024-09-23 清除定时闹钟
     */
    ClearAlarm();

    /**
     * @since 2024-09-24 浏览器关闭，导致无法及时通知，超过60分钟，不通知
     */
    if(diff >= -3600){
      /**
       * @since 2025-11-28 突出提示END结束，用户点击按钮或者图标，清空END标志
       */
      BarTextTime("END");

      /**
       * @since 2024-09-30 获取用户配置，结束的通知方式
       */
      const config = await GetUserConfig();
      // console.log("用户配置", config);

      for(let i in config["notification"]){
        // console.log("通知方式", config["notification"][i]);
        switch (config["notification"][i]){
          case "tab":
            /**
             * @since 2024-09-29 新页面，open tab，用户经常看不到
             * @since 2025-09-04 弹出页面，确保用户看到
             */
            // chrome.tabs.create({url: chrome.runtime.getURL("../../pages/notification.html")});
            const w = 400, h = 250;
            const win = await chrome.windows.getCurrent();
            const left = win.left + Math.round((win.width - w) / 2);
            const top = win.top + Math.round((win.height - h) / 2);
            const p = {
              width: w,
              height: h,
              type: 'popup',
              left: left,
              top: top,
              url: chrome.runtime.getURL("pages/notification.html")
            };
            chrome.windows.create(p);
            break;
          case "bar":
            /**
             * @since 2024-09-27 超过1分钟，增加超时提醒
             */
            let timeoutMessage = "";
            if(diff <= -60){
              timeoutMessage = chrome.i18n.getMessage("timeout_reminder").replace("100", parseInt(Math.abs(diff)/60));
            } else {}
            // console.log("超时信息", timeoutMessage);

            /**
             * @since 2025-11-24 提示框的图标
             */
            let iconPath = chrome.runtime.getURL("assets/images/icon_128.png");
            if(config["theme-mode"] == "dark"){
              iconPath = chrome.runtime.getURL("assets/images/icon_128_dark.png");
            } else {}

            /**
             * @since 2024-09-24 消息提醒，倒计时结束
             */
            let msg = chrome.i18n.getMessage("countdown_has_ended").replace(chrome.i18n.getMessage("time_replace"), HumanTime(timer.countdowntime)) + timeoutMessage;
            // console.log("通知栏信息", msg);
            chrome.notifications.create('', {
              type: 'basic',
              iconUrl: iconPath,
              title: chrome.i18n.getMessage("notification_bar_title"),
              message: msg
            });
            break;
          default:
            /**
             * @since 2025-09-05 未知提醒方式
             */
        }
      }
    } else {
      /**
       * @since 2025-11-27 超过60分钟，不做任何提示
       */
      BarTextTime("");
    }
  }
}

/**
 * @description 插件栏图标显示信息
 * @author start2004
 * @since 2024-09-23
 *
 * @param {int} sec 图标上显示的数字，单位秒
 * @param {string} bgColor 背景色
 * @return {null}
 */
function BarTextTime(sec, bgColor){
  if(bgColor === undefined) bgColor = "#1A1A1A";
  let barTime = BarTime(sec);
  // console.log("插件栏显示", barTime);

  /**
   * @since 2025-09-03 设置6次相同信息，不更新barText，即1分钟更新1次
   */
  let updateText = barTime + bgColor;
  if(badgeText == updateText){
    if(sameTextCount <= 6){
      sameTextCount++;
      return ;
    } else {
      sameTextCount = 1;
    }
  } else {
    badgeText = updateText;
    sameTextCount = 1;
  }

  /**
   * @since 2025-09-03 显示测试信息
   */
  if(sec == 0){
    console.log("显示图标的次数", showCount);
    showCount = 0;
  } else {
    // console.log("更新图标", barTime);
    showCount++;
  }

  /**
   * @since 2025-08-29 局部优化
   * @since 2025-08-29 确定要显示，再把倒计时秒数改成，5m, 5s
   */
  chrome.action.setBadgeBackgroundColor({ color: bgColor });
  chrome.action.setBadgeTextColor({ color: '#F5F5F5' });
  chrome.action.setBadgeText({text: barTime});
}

/**
 * @description 创建定时闹钟
 * @author start2004
 * @since 2025-09-03
 *
 * @param {int} sec 闹钟间隔秒数
 */
async function CreateAlarm(sec){
  /**
   * @since 2025-09-03 检查闹钟是否存在
   */
  const exists = await CheckAlarmExists();
  if(exists) ClearAlarm();

  /**
   * @since 2025-09-03 创建闹钟
   */
  chrome.alarms.create(alarmName, {
      periodInMinutes: sec/60
  });
  alarmTime = sec;
}

/**
 * @description 清理定时闹钟
 * @author start2004
 * @since 2024-09-24
 *
 * @return {null}
 */
function ClearAlarm(){
  chrome.alarms.clear(alarmName, (wasCleared) => {});
  alarmTime = 0;
}

/**
 * @description 检查定时闹钟是否存在
 * @author start2004
 * @since 2025-09-03
 *
 * @return {boolean}
 */
function CheckAlarmExists() {
    return new Promise((resolve) => {
        chrome.alarms.get(alarmName, (alarm) => {
            // 如果alarm存在则返回true，否则返回false
            resolve(!!alarm);
        });
    });
}

/**
 * @description 监听闹钟任务，执行
 * @author start2004
 * @since 2025-09-03
 */
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === alarmName) UpdateTimeBar();
});

/**
 * @description 监听popup透传信息
 * @author start2004
 * @since 2024-09-23
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "update-timer") {
    /**
     * @since 2024-10-30 透传过来，更新图标文字
     */
    timer = message.data;
    UpdateTimeBar();
  } else {}
  // return true;
});

/**
 * @description 浏览器启动时触发
 * @author start2004
 * @since 2024-09-24
 */
chrome.runtime.onStartup.addListener(async() => {
  /**
   * @since 2025-11-04 设置图标
   */
  let userConfig = await GetUserConfig();
  setIcon(userConfig);

  // console.log("浏览器启动触发 UpdateTimeBar");
  setTimeout(function (){
    UpdateTimeBar();
  }, 2000);
});

/**
 * @since 2024-11-14 备注说明
 * 在实际中，直接执行UpdateTimeBar比浏览器启动触发OnStartup快一些
 * 如果为了确保启动成功，2次事件都触发执行UpdateTimeBar，在 浏览器被关闭再打开 且 任务已经结束，会触发执行打开网页2次
 * 这里setTimeout延迟执行，否则太快，会导致chrome.notifications.create失败，推测可能是chrome服务未启动导致
 */
// console.log("直接触发执行UpdateTimeBar");
// setTimeout(function (){UpdateTimeBar();}, 2000);
